package com.wfit.boot.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wfit.boot.common.Constants;
import com.wfit.boot.common.Result;
import com.wfit.boot.controller.dto.UserDTO;
import com.wfit.boot.entity.User;
import com.wfit.boot.service.UserService;
import com.wfit.boot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
//    @Autowired
//    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @GetMapping
    public List<User> findall(){

        return userService.list();
    }
    @GetMapping("/username/{username}")
    public Result findOne(@PathVariable String username){
QueryWrapper<User> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("username",username);
return Result.success(userService.getOne(queryWrapper));
    }
    @PostMapping
    public Result save(@RequestBody User user){
        return Result.success(userService.saveUser(user));
    }
@DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
    boolean b = userService.removeById(id);
    return Result.success(b);
}
    @PostMapping("/del/batch")
    public Result deletebatch(@RequestBody List<Integer> ids){

        return Result.success(userService.removeByIds(ids));
    }
//    @GetMapping("/page")
//    public Map<String,Object> findPage(@RequestParam Integer pageNum,
//                        @RequestParam Integer pageSize,
//                        @RequestParam String username){
//pageNum=(pageNum-1)*pageSize;
//username="%"+username+"%";
//List<User> data = userMapper.selectPage(pageNum, pageSize,username);
//Integer total=userMapper.selectPageTotal(username);
//        Map<String ,Object> res=new HashMap<>();
//res.put("data",data);
//        res.put("total",total);
//        return res;
//    }
@GetMapping("/page")
public Result findPage(@RequestParam Integer pageNum,
                    @RequestParam Integer pageSize,
                    @RequestParam(defaultValue = "") String username,
                            @RequestParam(defaultValue = "") String nickname){
    IPage<User> page =new Page<>(pageNum,pageSize);
    QueryWrapper<User> queryWrapper=new QueryWrapper<>();
    queryWrapper.orderByDesc("id");
    if (!"".equals(username)){
        queryWrapper.like("username",username);
    }
    if (!"".equals(nickname)){
        queryWrapper.like("nickname",nickname);
    }


    User currentUser=TokenUtils.getCurrentUser();
    System.out.println("获取当前用户信息++++++++=====+++++" + currentUser.getNickname());


     return Result.success(userService.page(page,queryWrapper));

}
@GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        List<User> list =userService.list();
    ExcelWriter writer = ExcelUtil.getWriter(true);
    writer.addHeaderAlias("username","用户名");
    writer.addHeaderAlias("password","密码");
    writer.addHeaderAlias("email","邮箱");
    writer.addHeaderAlias("phone","电话");
    writer.addHeaderAlias("address","地址");
    writer.addHeaderAlias("nickname","昵称");
    writer.addHeaderAlias("create_time","创建时间");
    writer.addHeaderAlias("avatarurl","头像");

    writer.write(list,true);

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
    String fileName = URLEncoder.encode("用户信息", "UTF-8");
    response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

    ServletOutputStream out = response.getOutputStream();
    writer.flush(out, true);
    out.close();
    writer.close();
    }
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
//List<User> list =reader.readAll(User.class);
//        List<User> list = reader.read(0, 1, User.class);
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            users.add(user);
        }
        userService.saveBatch(users);
        return Result.success(true);
    }
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO){
       String username=userDTO.getUsername();
       String password=userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
return Result.error(Constants.CODE_400,"参数错误");
        }
UserDTO dto=userService.login(userDTO);
        return Result.success(dto);
    }
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        String username=userDTO.getUsername();
        String password=userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }
        return Result.success(userService.register(userDTO));
    }
}
